import {listRegion} from '../api/business/region';
import {listVillage} from "../api/business/village";

import {listUnits} from '../api/business/units';
import {listHouse} from "../api/business/house";
import {listBuilding} from "../api/business/building";


const OPTIONS_DATA_MAP = {
  "REGIONS": listRegion,
  "VILLAGES": listVillage,
  "UNITS": listUnits,
  "HOUSES": listHouse,
  "BUILDINGS": listBuilding
}

// 全局是否可缓存，不传默认开启缓存
let GLOBAL_CACHEABLE = false;

export default {

  // 根据key获取options data
  getOptions: async function (key, param, cacheable) {
    // 逻辑验证
    if (cacheable === undefined) {
      cacheable = GLOBAL_CACHEABLE;
    }
    if (cacheable) {
      let tempKey = key;
      if (param) {
        tempKey = key + JSON.stringify(param);
      }
      let optionsDataString = sessionStorage.getItem(tempKey);
      if (optionsDataString) {
        let data = JSON.parse(optionsDataString);
        console.log("使用缓存", JSON.parse(optionsDataString));
        if (data instanceof Array) {
          if (data.length !== 0) {
            return JSON.parse(optionsDataString);
          }
        } else {
          return JSON.parse(optionsDataString);
        }
      }
    }
    console.log("业务下拉数据" + key + "尚未被缓存或禁用缓存，获取远端数据中...");
    console.log(OPTIONS_DATA_MAP[key])
    let { rows } = await OPTIONS_DATA_MAP[key](param || {});
    sessionStorage.setItem(param ? key + JSON.stringify(param) : key, JSON.stringify(rows));
    return rows;
  },
  getLabel: function (val, dataList, valKey, labelKey) {
    let filter = dataList.filter(item => item[valKey] === val);
    return filter && filter[0] && filter[0][labelKey];
  },
  getItem: function (val, dataList, valKey) {
    let filter = dataList.filter(item => item[valKey] === val);
    return filter && filter[0];
  }


}
